import axios from 'axios'
import { ElMessage } from 'element-plus'
import { __joinObj } from './common'

const { VITE_APPKEY, VITE_BASE_URL } = import.meta.env

const service = axios.create({
  timeout: 20000,
  baseURL: VITE_BASE_URL
})
service.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'

/**
 *
 * @param {function} res  响应成功时的回调
 */
const responseSuccess = (res: any) => {
  if (res.config.systemType && res.data.code !== 200) {
    return ElMessage.error('无权限访问')
  }
  switch (res.data.code) {
    case 400:
      ElMessage.error('非法请求，签名sign验证失败')
      break
    case 401:
      ElMessage.error('您还没有登录呢，请您先登录')
      localStorage.removeItem('Authorization')
      break
    case 403:
      ElMessage.error('您没有权限访问')
      break
    case 500:
    case 100:
      ElMessage.error(res.data.message || '抱歉，当前值班小哥翘班了，我们马上报告老板！')
      break
  }
  return Promise.resolve(res.data)
}

/**
 *
 * @param {function} err 响应失败时的回调
 */
const responseFail = (err: any) => {
  if (err.response.config.systemType) {
    return ElMessage.error('无权限访问')
  }
  // 断网 或者 请求超时 状态
  if (!err.response) {
    // 请求超时状态
    if (err.message.includes('timeout')) {
      ElMessage.error('请求超时，请检查网络是否连接正常')
    } else {
      ElMessage.error('请求失败，请检查网络是否已连接')
    }
    return
  }
  // 判断服务器返回不是 2 开头的情况
  const responseCode = err.response.status
  switch (responseCode) {
    case 401:
      ElMessage.error('请重新登录')
      localStorage.removeItem('Authorization')
      location.href = '/outside/login'
      break
    case 403:
      ElMessage.error('接口无权限访问')
      break
    case 404:
      ElMessage.error('接口不存在')
      break
    default:
      ElMessage.error(err.response.data.message)
  }
  return Promise.reject(err)
}

/**
 * 请求拦截
 */
service.interceptors.request.use((config: any) => {
  if (config.systemType === 'open') {
    return config
  }
  let params = config.params ? config.params : {}
  Object.keys(params).forEach(item => {
    if (params[item] === null || params[item] === undefined) {
      delete params[item]
    }
  })
  params.appKey = VITE_APPKEY
  // 当前时间戳
  params.timestamp = Date.now()

  // 生成签名
  params.sign = __joinObj({ ...params })
  config.params = params
  config.headers['Authorization'] = localStorage.getItem('Authorization')
  config.headers['x-st'] = 'WMS'
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
service.interceptors.response.use(
  responseSuccess,
  responseFail
)

export default service
